package com.DHH.Controller.Api;

import com.DHH.BikeAction.BikeResult;
import com.DHH.BikeAction.BikeUnlockResult;
import com.DHH.BikeAction.DHHRequest;
import com.DHH.Config.ApiConstant;
import com.DHH.Config.Constant;
import com.DHH.Config.DHHConstant;
import com.DHH.Dto.ApiBikeMessage;
import com.DHH.Dto.Message;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Device.BikeLatest;
import com.DHH.Entity.Device.Device;
import com.DHH.Entity.Device.Dmap;
import com.DHH.Entity.Order.OrderInfo;
import com.DHH.Mapper.Api.ApiDeviceMapper;
import com.DHH.Mapper.Api.Order.ApiOrderInfoMapper;
import com.DHH.Mapper.Device.BikeLatestMapper;
import com.DHH.Mapper.Device.DmapMapper;
import com.DHH.Service.Api.ApiOrderServices;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 汪玉东 on 2017/8/26.
 */
@Controller
@RequestMapping("/api/bike/")
public class BikeController {
    @Resource
    private ApiOrderServices apiOrderServices;
    @Resource
    private DmapMapper dmapMapper;
    @Resource
    private ApiOrderInfoMapper apiOrderInfoMapper;

    @Resource
    private ApiDeviceMapper apiDeviceMapper;
    @Resource
    private BikeLatestMapper bikeLatestMapper;



    @RequestMapping("getBikeDetail")
    @ResponseBody
    public Message getBikeDetail(String device_id, HttpSession session){
        Message message=new Message();
        try{
            Dmap dmap=new Dmap();
            dmap.setDhhid(device_id);

            dmap=dmapMapper.selectOne(dmap);
            if(dmap!=null&&dmap.getUdid()!=null){
                device_id=dmap.getUdid();
            }

            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setUdid(device_id);
            bikeLatest=bikeLatestMapper.selectOne(bikeLatest);
            message.setState(true);
            message.setData(bikeLatest);
        }catch (Exception e){
            message.setState(false);
            message.setMsg("失败");
        }
        return  message;
    }

    @RequestMapping("checkUnlockResult")
    @ResponseBody
    public ApiBikeMessage checkUnlockResult(String device_id, HttpSession session){
        ApiBikeMessage message=new ApiBikeMessage();
        Dmap dmap=new Dmap();
        dmap.setDhhid(device_id);

        dmap=dmapMapper.selectOne(dmap);
        if(dmap!=null&&dmap.getUdid()!=null){
            device_id=dmap.getUdid();
        }
        BikeLatest bikeLatest=new BikeLatest();
        bikeLatest.setUdid(device_id);
        bikeLatest=bikeLatestMapper.selectOne(bikeLatest);

        message.setStatus(bikeLatest.getEvLock());
        message.setMessage("获取成功");
        return message;
    }



    @RequestMapping("conride")
    @ResponseBody
    public  ApiBikeMessage keepOnRiding(Integer orderId,HttpSession session){
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo=apiOrderInfoMapper.selectByPrimaryKey(orderInfo);
        return unlock("",orderInfo.getDeviceId(),"",session);
    }

    @RequestMapping("unlockByOrder")
    @ResponseBody
    public  ApiBikeMessage unlockByOrder(Integer orderId,HttpSession session){
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        try{
            OrderInfo orderInfo=new OrderInfo();
            orderInfo.setId(orderId);
            orderInfo=apiOrderInfoMapper.selectOne(orderInfo);
            orderInfo.getDeviceId();
            DHHRequest dhhRequest=new DHHRequest();
            dhhRequest.setCtl(DHHConstant.API_ctl_action4);
            dhhRequest.setUdid(orderInfo.getDeviceId());
            BikeResult bikeResult=dhhRequest.baseRequest();

            if(bikeResult.getCode().equals("200")){
                apiBikeMessage.setStatus(1);
                apiBikeMessage.setMessage("请求成功");
            }
        }catch (Exception e){
            apiBikeMessage.setStatus(-1);
            apiBikeMessage.setMessage("未知错误");
        }
        return apiBikeMessage;
    }

    @RequestMapping("unlock")
    @ResponseBody
    public ApiBikeMessage unlock(String token, String device_id, String checksum, HttpSession session){

       try{
           BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
           ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
           if(baseUser==null){
               apiBikeMessage.setStatus(-3);
               apiBikeMessage.setMessage("登录失效");
               return  apiBikeMessage;
           }
           Dmap dmap=new Dmap();
           dmap.setDhhid(device_id);
           dmap=dmapMapper.selectOne(dmap);
          if(dmap!=null&&dmap.getUdid()!=null){
              device_id=dmap.getUdid();
          }
           if(!isCanUnLock(device_id,baseUser)){
               apiBikeMessage.setStatus(3);
               apiBikeMessage.setMessage("当前车辆已在骑行状态");
               return  apiBikeMessage;
           }
           DHHRequest dhhRequest=new DHHRequest();
           dhhRequest.setCtl(DHHConstant.API_ctl_action4);
           dhhRequest.setUdid(device_id);
           BikeResult bikeResult=dhhRequest.baseRequest();

           if(bikeResult.getMsg()!=null){
               apiBikeMessage.setMessage(bikeResult.getMsg());
           }
           if(bikeResult.getCode().equals("200")){
               //ApiBikeMessage apiBikeMessage1=checkUnlockResult(device_id,session);
               if(true){
                   apiOrderServices.insert(device_id,"0","0",baseUser);
                   apiBikeMessage.setStatus(1);
                   apiBikeMessage.setMessage("开锁成功");
                   BikeUnlockResult bikeUnlockResult=new BikeUnlockResult();
                   bikeUnlockResult.setSerial_no("0001");
                   apiBikeMessage.setResult(bikeUnlockResult);
               }else{
                   apiBikeMessage.setStatus(3);
                   apiBikeMessage.setMessage("指令发送成功但[开锁失败]");
               }
           }else{
               apiBikeMessage.setStatus(3);
               apiBikeMessage.setMessage("指令发送失败");
           }
           return  apiBikeMessage;
       }catch (Exception e){
           ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
           apiBikeMessage.setStatus(3);
           apiBikeMessage.setMessage(e.getMessage());
           return  apiBikeMessage;
       }
    }


    private boolean isCanUnLock(String did,BaseUser baseUser){
        Map map=new HashMap();
        map.put("did",did);
        map.put("state1","ddwc");
        map.put("state2","tc");
        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByDidAndState(map);
//        System.out.println("12312321321321321312321321");
//        System.out.println(orderInfo);
//        System.out.println(baseUser);
//        System.out.println("123123213213213213");
        if(orderInfo==null){
            return true;
        }else{
            if(orderInfo.getUserId()==baseUser.getId()){
                return true;
            }
            return false;
        }
    }

    @RequestMapping("lock")
    @ResponseBody
    public ApiBikeMessage lock(String token, String device_id, String checksum, HttpSession session){
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        if(baseUser==null){
            apiBikeMessage.setStatus(-3);
            apiBikeMessage.setMessage("登录失效");
            return  apiBikeMessage;
        }
        Map map=new HashMap();
        map.put("userId",baseUser.getId());
        map.put("state1","ddwc");
        map.put("state2","tc");
        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByUserAndState(map);
        if(!isCanlock(orderInfo.getDeviceId())){
            apiBikeMessage.setStatus(-1);
            apiBikeMessage.setMessage("不在停车范围内");
            return  apiBikeMessage;
        }
        DHHRequest dhhRequest=new DHHRequest();
        dhhRequest.setCtl(DHHConstant.API_ctl_action3);
        dhhRequest.setUdid(device_id);
        BikeResult bikeResult=dhhRequest.baseRequest();

        if(bikeResult.getMsg()!=null){
            apiBikeMessage.setMessage(bikeResult.getMsg());
        }
        if(bikeResult.getCode().equals("200")){
            apiBikeMessage.setStatus(1);
            apiBikeMessage.setMessage("关锁成功");
            BikeUnlockResult bikeUnlockResult=new BikeUnlockResult();
            bikeUnlockResult.setSerial_no(orderInfo.getId().toString());
            apiBikeMessage.setResult(bikeUnlockResult);
            apiOrderServices.updateOrderSettlement(orderInfo,"tc");
        }else{
            apiBikeMessage.setStatus(3);
        }
        return  apiBikeMessage;
    }


    @RequestMapping("bikeList")
    @ResponseBody
    public ApiBikeMessage bikeList(Double longitude,Double latitude){
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        Example example=new Example(Device.class);

        example.createCriteria()
                .andBetween("lat",latitude- ApiConstant.WX_MAP_RADIO,latitude+ApiConstant.WX_MAP_RADIO)
                .andBetween("lng",longitude-ApiConstant.WX_MAP_RADIO,longitude+ApiConstant.WX_MAP_RADIO);
        List<Device> rs= apiDeviceMapper.selectByExample(example);
        System.out.println(rs);
        apiBikeMessage.setMessage("请求成功");
        apiBikeMessage.setStatus(1);
        apiBikeMessage.setResult(rs);
        return  apiBikeMessage;
    }



    @RequestMapping("queryCurrentScene")
    @ResponseBody
    public  ApiBikeMessage queryCurrentScene(HttpSession session){
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        if(baseUser==null){
            apiBikeMessage.setStatus(-3);
            apiBikeMessage.setMessage("登录失效");
            return  apiBikeMessage;
        }

        Map map=new HashMap();
        map.put("userId",baseUser.getId());
        map.put("state1","ddwc");
        map.put("state2","tc");
        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByUserAndState(map);
       if( isCanlock(orderInfo.getDeviceId())){
           apiBikeMessage.setStatus(1);
           apiBikeMessage.setMessage("在停车范围内");
           return  apiBikeMessage;
       }
        apiBikeMessage.setStatus(0);
        apiBikeMessage.setMessage("不在停车范围内");
        return  apiBikeMessage;
    }

    private boolean isCanlock(String uid){
        Device device=new Device();
        device.setUdid(uid);
        device= apiDeviceMapper.queryCurrentSceneByDid(device);
        if(device!=null&&device.getId()!=null){
            return  true;
        }else{
            return false;
        }
    }


    @RequestMapping("curlock")
    @ResponseBody
    public ApiBikeMessage curlock(String token, String device_id, String checksum, HttpSession session){
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        if(baseUser==null){
            apiBikeMessage.setStatus(-3);
            apiBikeMessage.setMessage("登录失效");
            return  apiBikeMessage;
        }
        Map map=new HashMap();
        map.put("userId",baseUser.getId());
        map.put("state1","ddwc");
        map.put("state2","tc");

        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByUserAndState(map);

        if(orderInfo.getStateId()==2){
            return curUnlock(orderInfo);
        }

        DHHRequest dhhRequest=new DHHRequest();
        dhhRequest.setCtl(DHHConstant.API_ctl_action3);
        dhhRequest.setUdid(device_id);
        BikeResult bikeResult=dhhRequest.baseRequest();



        if(bikeResult.getMsg()!=null){
            apiBikeMessage.setMessage(bikeResult.getMsg());
        }
        if(bikeResult.getCode().equals("200")){
            apiBikeMessage.setStatus(1);
            apiBikeMessage.setMessage("关锁成功");
            BikeUnlockResult bikeUnlockResult=new BikeUnlockResult();
            bikeUnlockResult.setSerial_no(orderInfo.getId().toString());
            apiBikeMessage.setResult(bikeUnlockResult);
            apiOrderServices.updateOrderSettlement(orderInfo,"lstc");
        }else{
            apiBikeMessage.setStatus(3);
        }
        return  apiBikeMessage;
    }


    private ApiBikeMessage curUnlock(OrderInfo orderInfo){
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        DHHRequest dhhRequest=new DHHRequest();
        dhhRequest.setCtl(DHHConstant.API_ctl_action4);
        dhhRequest.setUdid(orderInfo.getDeviceId());
        BikeResult bikeResult=dhhRequest.baseRequest();
        if(bikeResult.getMsg()!=null){
            apiBikeMessage.setMessage(bikeResult.getMsg());
        }
        if(bikeResult.getCode().equals("200")){
            apiBikeMessage.setStatus(1);
            apiBikeMessage.setMessage("开锁成功");
            BikeUnlockResult bikeUnlockResult=new BikeUnlockResult();
            bikeUnlockResult.setSerial_no(orderInfo.getId().toString());
            apiBikeMessage.setResult(bikeUnlockResult);
            apiOrderServices.updateOrderKeepOn(orderInfo);
        }else{
            apiBikeMessage.setStatus(3);
        }
        return  apiBikeMessage;

    }

}
